//
//  ActivityViewController.m
//  yunyan
//
//  Created by haichuang on 2018/2/11.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "ActivityViewController.h"
#import "ActiveListCell.h"
#import "TopHeaderView.h"
#import "ActiveDetailViewController.h"
#import "IssueViewController.h"
#import "PublishActViewController.h"

@interface ActivityViewController () <UITableViewDelegate, UITableViewDataSource>{
    
    int page;
    NSMutableArray * _dataArray;
}
@property (nonatomic, strong) UITableView * activeTableview;
@property (nonatomic, strong) TopHeaderView * topHearderView;

@end

@implementation ActivityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    _dataArray = @[].mutableCopy;
    // Do any additional setup after loading the view.
    [self createTab];
     [self customNaviItemTitle:@"活动" isLeft:NO];
    [self customTabBarButtonTitle:@"发布" image:nil target:self action:@selector(rightButtonEvent) isLeft:NO];
    [self getActListRequest];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createTab{
    WeakSelf;
    _activeTableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:_activeTableview];
  
    [_activeTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.equalTo (weakSelf.view);

    }];
    _activeTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _activeTableview.delegate = self;
    _activeTableview.dataSource = self;
    _activeTableview.estimatedRowHeight = 254.f;
    _activeTableview.rowHeight = UITableViewAutomaticDimension;
    [_activeTableview registerNib:[UINib nibWithNibName:@"ActiveListCell" bundle:nil] forCellReuseIdentifier:@"ActiveListCell"];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        page =1;
        [self getActListRequest];
        
    }];
    _activeTableview.mj_header =header;
    
        MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
              page++;
              [self getActListRequest];
        }];
    
       _activeTableview.mj_footer =footer;

}

#pragma mark- btn
-(void)rightButtonEvent{
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
        
        PublishActViewController*  issueVC = [[PublishActViewController alloc] init];
        issueVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:issueVC animated:YES ];
        
//        IssueViewController * issueVC = [[IssueViewController alloc] init];
//        issueVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:issueVC animated:YES ];
    }else {
        LoginViewController *loginVC = [LoginViewController new];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navc animated:YES completion:nil];
    }
   
}

#pragma mark-UITableViewDelegate, UITableViewDataSource


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 66.f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    _topHearderView = [[TopHeaderView alloc]init];
    _topHearderView.timeLabel .hidden = YES;
     NSDictionary * dic = _dataArray[section];
    [_topHearderView.headImage sd_setImageWithURL:ImageUrl(dic[@"head_url"]) placeholderImage:ImageName(@"")];
    _topHearderView.titleLabel.text = dic[@"user_nick"];
    
    return _topHearderView;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = _dataArray[indexPath.section];
    
    ActiveListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ActiveListCell" forIndexPath:indexPath];
    [cell.actImage sd_setImageWithURL:ImageUrl(dic[@"cover_pic"]) placeholderImage:ImageName(@"")];
    cell.actImage.contentMode=UIViewContentModeScaleAspectFill;
    cell.actImage.clipsToBounds=YES;
    cell.titleLabel.text = dic[@"title"];
    cell.commentNumber.text = [NSString stringWithFormat:@"%ld",[dic[@"comment_num"] integerValue]];
    cell.lookNumber.text = [NSString stringWithFormat:@"%ld",[dic[@"view_num"] integerValue]];
    cell.timeLabel.text = dic[@"create_time"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
 
    return cell;
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = _dataArray[indexPath.section];
    
    [self getActDetailsRequestForid:[NSString stringWithFormat:@"%ld",[dic[@"id"] integerValue]]];
    
}

-(void)getActDetailsRequestForid:(NSString *)newsId{
    
    
    NSString * user_id = [NSString stringWithFormat:@"%ld",[USER_DEFAULTGet(@"user_id")  integerValue]];
    if (user_id.length>1) {
        
    }else {
        user_id=@"";
    }


    NSDictionary * dic = @{@"news_id":newsId,
                           @"user_id":user_id
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(activity_details_api) andparameters:dic Success:^(id responseObject) {
        
       NSDictionary *  dataDic = responseObject;
        NSLog(@"responseObject = %@",responseObject);
        
       
        
        NSLog(@"responseObject = %@",responseObject);
        
        USER_DEFAULTSet(dataDic[@"pic_url"], @"actDetailsIamgeArray");
        USER_DEFAULTSet(dataDic[@"is_fabulous"], @"act_is_fabulous");
        
        
        if ([dataDic[@"pic_url"] isKindOfClass:[NSArray class]]) {
            NSArray * array = dataDic[@"pic_url"];
            if (array.count==0) {
                
                USER_DEFAULTSet(@"http://a1.qpic.cn/psb?/V147v55d35m6eX/xXdZ2De4s1iE5gYJaikuWyqltDsmFf*LHHZ1ANFPtso!/m/dDABAAAAAAAA&bo=eAB4AAAAAAADByI!&rf=photolist", @"shareImage");
            }else {
                
                USER_DEFAULTSet(dataDic[@"pic_url"][0], @"shareImage");
            }
        }
        NSString * newsId= [NSString stringWithFormat:@"%ld",[dataDic[@"id"] integerValue]];
        USER_DEFAULTSet(newsId,@"shareNewsId");
        USER_DEFAULTSet(@"2",@"shareType");
        USER_DEFAULTSet(dataDic[@"title"], @"shareTitle");
        USER_DEFAULTSet(dataDic[@"content"], @"shareContent");
        USER_DEFAULTSet(dataDic[@"share_url"], @"shareUrl");
        
        
        ActiveDetailViewController * activeDetail = [[ActiveDetailViewController alloc]init];
        activeDetail.actIdStr = newsId;
        activeDetail.dataDic = dataDic;
        activeDetail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:activeDetail animated:YES];
        
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
      
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

-(void)getActListRequest{
    
    NSDictionary * dic = @{@"page":[NSString stringWithFormat:@"%d",page],
                           };
    
  
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_activityList_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray * array = responseObject;
            if (page == 1) {
                if (_dataArray) {
                    [_dataArray removeAllObjects];
                }
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }else {
                for (NSDictionary * dic in array) {
                    
                    [_dataArray addObject:dic];
                }
            }
            
            [self.activeTableview reloadData];
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"msg"]);
        }
        
        [self.activeTableview.mj_header endRefreshing];
        [self.activeTableview.mj_footer endRefreshing];
        NSLog(@"responseObject = %@",responseObject);
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        [self.activeTableview.mj_header endRefreshing];
        [self.activeTableview.mj_footer endRefreshing];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
//            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
